package com.video.web.service;

import com.video.common.constant.Constants;
import com.video.common.core.domain.AjaxResult;
import com.video.common.exception.ServiceException;
import com.video.common.utils.InvitationCodeUtil;
import com.video.common.utils.sign.Md5Utils;
import com.video.framework.web.service.TokenService;
import com.video.video.domain.DUser;
import com.video.video.domain.RegisterSettings;
import com.video.video.domain.app.dto.AppUserRegisterDto;
import com.video.video.domain.app.dto.LoginDto;
import com.video.video.domain.app.dto.RePasswordDto;
import com.video.video.domain.app.dto.UserInfoDto;
import com.video.video.service.IDUserService;
import com.video.video.service.IRegisterSettingsService;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

@Service
public class AppDUserService {
  private Logger logger = LoggerFactory.getLogger(getClass());
  @Resource
  private IDUserService userService;
  @Autowired
  private TokenService tokenService;
  @Autowired
  private IRegisterSettingsService registerSettingsService;

  /**
   * 注册
   * */
  public DUser register(AppUserRegisterDto appUserRegisterDto) {
    //获取注册设置
    List<RegisterSettings> list = registerSettingsService.selectRegisterSettingsList(new RegisterSettings());
    RegisterSettings registerSettings=new RegisterSettings();
    if(CollectionUtils.isNotEmpty(list)){
      registerSettings=list.get(0);
    }else {
      throw new ServiceException("系统未设置注册信息", 10081);
    }
    //判断用户昵称是否必填
    if(registerSettings.getUsernameFill().equals("Y")){
      if (StringUtils.isEmpty(appUserRegisterDto.getUsername())) {
        throw new ServiceException("用户昵称不能为空", 10081);
      }
    }

    //密码
    if(registerSettings.getPasswordFill().equals("Y")){
      if (StringUtils.isEmpty(appUserRegisterDto.getPassword())) {
        throw new ServiceException("密码不能为空", 10081);
      }
      if (appUserRegisterDto.getPassword().length() > 10 || appUserRegisterDto.getPassword().length() < 6) {
        throw new ServiceException("密码至少6位,最大10位", 10082);
      }

    }
    //确认密码
    if(registerSettings.getRepasswordFill().equals("Y")){
      if (StringUtils.isEmpty(appUserRegisterDto.getRepassword())) {
        throw new ServiceException("确认密码不能为空", 10081);
      }
      if (appUserRegisterDto.getRepassword().length() > 10 || appUserRegisterDto.getRepassword().length() < 6) {
        throw new ServiceException("确认密码至少6位,最大10位", 10082);
      }
      if(!appUserRegisterDto.getPassword().equals(appUserRegisterDto.getRepassword())){
        throw new ServiceException("设置密码与确认密码不相等", 10082);
      }

    }
    //手机号
    if(registerSettings.getMobileFill().equals("Y")){
      if (StringUtils.isEmpty(appUserRegisterDto.getMobile())) {
        throw new ServiceException("手机号不能为空", 10084);
      }
      DUser dUserM=new DUser();
      dUserM.setMobile(appUserRegisterDto.getMobile());
      List<DUser> userMlist=  userService.selectDUserAllList(dUserM);
      if(CollectionUtils.isNotEmpty(userMlist)){
        throw new ServiceException("电话号不能重复",10049);
      }
    }
    //验证码
    if(registerSettings.getCodeFill().equals("Y")){
      if (StringUtils.isEmpty(appUserRegisterDto.getCode())) {
        throw new ServiceException("验证码不能为空", 10083);
      }
      String phoneToken = String.format(Constants.PHONE_CODE_TOKEN,appUserRegisterDto.getMobile());//缓存key
      boolean isCheckCode = tokenService.checkCode(phoneToken,appUserRegisterDto.getCode()).booleanValue();
      if(!isCheckCode){
        throw new ServiceException("验证码不正确",10051);
      }

    }
    //真实姓名
    if(registerSettings.getRealnameFill().equals("Y")){
      if (StringUtils.isEmpty(appUserRegisterDto.getRealname())) {
        throw new ServiceException("真实姓名不能为空", 10077);
      }
      if (appUserRegisterDto.getRealname().length() > 50 || appUserRegisterDto.getRealname().length() < 2) {
        throw new ServiceException("真实姓名至少2位，最大50位", 10078);
      }
    }
    //性别
    if(registerSettings.getGenderFill().equals("Y")){
      if (StringUtils.isEmpty(appUserRegisterDto.getGender())) {
        throw new ServiceException("性别不能为空", 10077);
      }
    }
    //邮箱
    if(registerSettings.getEmailFill().equals("Y")){
      if (StringUtils.isEmpty(appUserRegisterDto.getEmail())) {
        throw new ServiceException("邮箱不能为空", 10079);
      }
      if (appUserRegisterDto.getEmail().split("@").length != 2) {
        throw new ServiceException("邮箱格式不正确", 10080);
      }
      DUser userEParam = new DUser();
      userEParam.setEmail(appUserRegisterDto.getEmail());
      List<DUser> userElist = userService.selectDUserAllList(userEParam);
      if(CollectionUtils.isNotEmpty(userElist)){
        throw new ServiceException("邮箱不能重复",10050);
      }

    }
    //邀请码
    if(registerSettings.getInvitationcodeFill().equals("Y")){
      if (StringUtils.isEmpty(appUserRegisterDto.getInvitationCode())) {
        throw new ServiceException("邀请码不能为空", 10079);
      }
    }

    DUser user = new DUser();
    user.setUsername(appUserRegisterDto.getUsername());
    user.setMobile(appUserRegisterDto.getMobile());
    String salt = Constants.SALT;
    user.setPassword(Md5Utils.hash(appUserRegisterDto.getPassword()+salt));
    user.setRealname(appUserRegisterDto.getRealname());
    user.setEmail(appUserRegisterDto.getEmail());
    user.setGender(appUserRegisterDto.getGender());
    user.setLevel("1");//会员等级：1 一般用户2 VIP用户3 SVIP 4 代理 5 合伙人
    user.setStatus("1");//用户状态 1启用 2禁用
    user.setCreateTime(new Date());

    //根据验证码获取用户id
    String invitationCode = appUserRegisterDto.getInvitationCode();
    if(StringUtils.isNotEmpty(invitationCode)){
      DUser userInvitaParam = new DUser();
      userInvitaParam.setInviteCode(invitationCode);
      List<DUser> userInvitationCode = userService.selectDUserAllList(userInvitaParam);
      if (userInvitationCode.size() != 1){
        throw new ServiceException("邀请码有误",10052);
      }
      user.setPid(userInvitationCode.get(0).getId());
    }else{
      user.setPid("0");
    }
    while (true){
      String code = InvitationCodeUtil.gen(Long.parseLong(System.currentTimeMillis()+""+(int)(Math.random() * 10000)),6);
      DUser userInvitaParam2 = new DUser();
      userInvitaParam2.setInviteCode(code);
      List<DUser> userList = userService.selectDUserAllList(userInvitaParam2);
      if (userList.size() == 0){
        user.setInviteCode(code);
        break;
      }
    }
    userService.insertDUser(user);
    return user;
  }

  /**
   * 登录验证
   * */
  public DUser login(LoginDto loginDto) {
    DUser user = new DUser();


    String mobile = loginDto.getUsername().replaceAll(" ","");
    user.setMobile(mobile);
    List<DUser> userList = userService.selectDUserAllList(user);
    if(CollectionUtils.isEmpty(userList)){
      throw new ServiceException("用户不存在",10053);
    }
    String pwd = Md5Utils.hash(loginDto.getPassword() + Constants.SALT);
    user.setPassword(pwd);
    userList = userService.selectDUserAllList(user);
    if(CollectionUtils.isEmpty(userList)){
      throw new ServiceException("密码不正确",10054);
    }
    return userList.get(0);
  }

  /**
   * 修改客户密码
   * */
  public int updatePassword(RePasswordDto dto){
    if(!StringUtils.equals(dto.getPassword(),dto.getRepassword())){
      throw new ServiceException("重复密码不匹配",10043);
    }
    if (dto.getPassword().length() > 10 || dto.getPassword().length() < 6) {
      throw new ServiceException("密码至少6位,最大10位", 10082);
    }
    String phoneToken = String.format(Constants.PHONE_CODE_TOKEN,dto.getMobile());//缓存key
    boolean isCode = tokenService.checkCode(phoneToken,dto.getCode());
    if(!isCode){
      throw new ServiceException("验证码错误",10044);
    }
    DUser user = new DUser();
    user.setId(dto.getId());
    String pwd = Md5Utils.hash(dto.getPassword() + Constants.SALT);
    user.setPassword(pwd);
    return userService.updateDUserInfo(user);
  }

  public int updateUserInfo(@Validated UserInfoDto dto){
    if (StringUtils.isEmpty(dto.getRealname())) {
      throw new ServiceException("真实姓名不能为空", 10077);
    }
    if (dto.getRealname().length() > 50 || dto.getRealname().length() < 2) {
      throw new ServiceException("真实姓名至少2位，最大50位", 10078);
    }
    if (StringUtils.isEmpty(dto.getEmail())) {
      throw new ServiceException("邮箱不能为空", 10079);
    }
    if (dto.getEmail().split("@").length != 2) {
      throw new ServiceException("邮箱格式不正确", 10080);
    }

    DUser user = new DUser();
    user.setId(dto.getId());
    user.setUsername(dto.getUsername());
    user.setRealname(dto.getRealname());
    user.setGender(dto.getGender());
    user.setHeadimg(dto.getHeadimg());
    user.setEmail(dto.getEmail());
    return userService.updateDUserInfo(user);
  }

}
